﻿var map;
var infoWindow;
var service;
var list = new Array();
var resultzzz;
var flag = true;
var ii = 0;
$(document).ready(function () {
    
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
    $(function () {
        var progressbar = $("#progressbar"),
      progressLabel = $(".progress-label");

        progressbar.progressbar({
            value: false,
            change: function () {
                progressLabel.text(progressbar.progressbar("value") + "%");
            },
            complete: function () {
                progressLabel.text("Complete!");
            }
        });

        //setTimeout( progress, 1 );
    });
});

function initialize() {

    var pyrmont = new google.maps.LatLng(parseFloat($("#text_lat").val()), parseFloat($("#text_lng").val()));
    map = new google.maps.Map(document.getElementById('map-canvas'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: pyrmont,
        zoom: parseInt($("#text_zoom").val())

    });

    infoWindow = new google.maps.InfoWindow();
    service = new google.maps.places.PlacesService(map);

    google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function progress() {
    var progressbar = $("#progressbar");
    var val = progressbar.progressbar("value") || 0;

    progressbar.progressbar("value", val + 1);

    if (val < 99) {
        setTimeout(progress, 40);
    } else {
        $('#button_new').removeAttr('disabled');
        if (ii < resultzzz.length)
            onclickNewButton();
        else
            $("#loading").html("Loading Completed ! (" + ii.toString() + "/" + resultzzz.length.toString() + ")");
    }
}




function performSearch() {
  var request = {
    bounds: map.getBounds(),
    keyword: $("#text_type").val()
  };
  service.radarSearch(request, callback);
}



function MyObject(lat, lng, icon, name, rating, vicinity, phoneNumber, address, url, website){
	this.lat = lat;
	this.lng = lng;
	this.icon = icon;
	this.name = name;
	this.rating = rating;
	this.vicinity = vicinity;
	this.phoneNumber = phoneNumber;
	this.address = address;
	this.url = url;
	this.website = website;
}

 function converttoascii(mystr)
 {
	var s = mystr;
    var VietnameseSigns = new Array();
    VietnameseSigns[0]= "aAeEoOuUiIdDyY";
    VietnameseSigns[1]="áàạảãâấầậẩẫăắằặẳẵ";
    VietnameseSigns[2]="ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ";
    VietnameseSigns[3]="éèẹẻẽêếềệểễ";
    VietnameseSigns[4]= "ÉÈẸẺẼÊẾỀỆỂỄ";
    VietnameseSigns[5]="óòọỏõôốồộổỗơớờợởỡ";
    VietnameseSigns[6]="ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ";
    VietnameseSigns[7]= "úùụủũưứừựửữ";
    VietnameseSigns[8]= "ÚÙỤỦŨƯỨỪỰỬỮ";
    VietnameseSigns[9]="íìịỉĩ";
    VietnameseSigns[10]="ÍÌỊỈĨ";
    VietnameseSigns[11]= "đ";
    VietnameseSigns[12]= "ĐÐ";
    VietnameseSigns[13]="ýỳỵỷỹ";
    VietnameseSigns[14] = "ÝỲỴỶỸ";
    for (var i = 1; i < VietnameseSigns.length; i++) {
        for (var j = 0; j < VietnameseSigns[i].length; j++) {
            var str = VietnameseSigns[i][j];
            s = s.split(str).join(VietnameseSigns[0][i - 1]);
        }
    }
    s = s.replace(/ /g, '');
    return s.toLowerCase();
 }

function loadIntoLayout(){
	var html = "";	
	for(var i = 0;i<list.length;i++){
  	var s=converttoascii(list[i].address);
	var t =converttoascii($("#text_street").val());
	if(s.toLowerCase().indexOf(t.toLowerCase())!=-1){
		html +="<tr><td>"+(i+1).toString()+"</td><td>"+list[i].name+"</td><td>"+list[i].address+"</td><td>"+list[i].lat.toFixed(6)+"</td><td>"+list[i].lng.toFixed(6)+"</td>";
			if(list[i].phoneNumber != null){
				html += "<td>" + list[i].phoneNumber+"</td>";
			} else {
				html += "<td>" + ""+"</td>";
			}
			if(list[i].website != null){
				html += "<td>"+list[i].website+"</td></tr>";
			} else {
				html += "<td>" + ""+"</td>";
			}
		}
	}
	
	return html;
}

function onclickButton(){
	initialize();
	list.splice(0,list.length);
	$("table").find("tr:gt(0)").remove();
	ii=0;
	
	$("#total").html("Total: " + resultzzz.length.toString() + " places");
}

function onclickNewButton(){

	$("#loading").html("Auto load detail places ("+ii.toString()+"/"+resultzzz.length.toString()+")...");
	 $('#button_new').attr('disabled','disabled');
	
	var progressbar = $( "#progressbar" );
	progressbar.progressbar( "value", 0 );	
		
	setTimeout( progress, 1 );
	
	for(var i = 0;i<10;i++){
		getDetailOfPlace(resultzzz[ii]);
		if(flag == false){
			flag = true;
			return;
		}
		ii++;
	}	
}


function getDetailOfPlace(place){
	service.getDetails(place, function(result, status) {
		  if (status != google.maps.places.PlacesServiceStatus.OK) {
		   // alert(status);
		   flag = false;
			return;
		  }
		  if(result){
			  var temp = new MyObject();
			  temp.lat = result.geometry.location.ob;
			  temp.lng = result.geometry.location.pb;
			  temp.icon = result.icon;
			  temp.name = result.name;
			  temp.rating = result.rating;
			  temp.vicinity = result.vicinity;
			  temp.phoneNumber = result.international_phone_number;
			  temp.address = result.formatted_address;
			  temp.url = result.url;
			  temp.website = result.website;
			  list.push(temp);
			  
			  
		
			$("table").find("tr:gt(0)").remove();
			$("#table").append(loadIntoLayout());
			
		  }
		});
}

function callback(results, status) {
	resultzzz = results;
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    alert(status);
    return;
  }
  for (var i = 0, resultz; resultz = results[i]; i++) {
    createMarker(resultz);
	
	
	
	
  }
  
  var html = loadIntoLayout();
  $("#table").append(html);
}

function createMarker(place) {
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
    icon: {
      // Star
      path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
      fillColor: '#ffff00',
      fillOpacity: 1,
      scale: 1/4,
      strokeColor: '#bd8d2c',
      strokeWeight: 1
    }
  });

  google.maps.event.addListener(marker, 'click', function() {
    service.getDetails(place, function(result, status) {
      if (status != google.maps.places.PlacesServiceStatus.OK) {
        alert(status);
        return;
      }
      infoWindow.setContent(result.name);
      infoWindow.open(map, marker);
    });
  });
}

